package com.example.demo.service;

import com.example.demo.pojo.Book;
import org.mengyun.tcctransaction.api.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;

@Service
public class BookService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Compensable(confirmMethod = "confirmBook", cancelMethod = "cancelBook", asyncConfirm = true)
//    @Transactional
    public void bugBook(Book book){
        var list=jdbcTemplate.query("select * from book where id = "+book.getId(),
                (rs, rowNum) -> new Book(rs.getInt(1),rs.getString(2),rs.getInt(3), rs.getInt(4)));
        if(list.size() < 1) {
            throw new RuntimeException("查不到对应商品.......");
        }
        var b = list.get(0);
        book.setTccNum(b.getNum());
        if(b.getNum() < 1 || b.getNum() < book.getNum()){
            throw new RuntimeException("库存不够.......");
        }
        b.setNum(b.getNum() - book.getNum());
        jdbcTemplate.execute("update book set num = "+b.getNum() +" where id = "+b.getId());
    }

    public void confirmBook(Book book){
        System.out.println("正常提交数据。。。。");
    }

    public void cancelBook(Book book){
        System.out.println("错误异常数据。。。。");
        jdbcTemplate.execute("update book set num = "+book.getTccNum()+", tcc_num = null where id = "+book.getId());
    }
}
